<template>
  <div class="ai-assistant">
    <!-- <AppHeader /> -->

    <main class="main-content">
      <div class="container">
        <div class="ai-layout">
          <!-- 左侧功能面板 -->
          <div class="sidebar">
            <div class="ai-features">
              <h3>AI功能</h3>
              <div class="feature-list">
                <div
                  v-for="feature in aiFeatures"
                  :key="feature.id"
                  class="feature-item"
                  :class="{ active: activeFeature === feature.id }"
                  @click="selectFeature(feature.id)"
                >
                  <el-icon :size="20">
                    <component :is="feature.icon" />
                  </el-icon>
                  <span>{{ feature.name }}</span>
                </div>
              </div>
            </div>

            <div class="quick-actions">
              <h4>快速操作</h4>
              <el-button size="small" @click="clearChat">清空对话</el-button>
              <el-button size="small" @click="exportChat">导出对话</el-button>
            </div>
          </div>

          <!-- 中央对话区域 -->
          <div class="chat-area">
            <div class="chat-header">
              <div class="ai-info">
                <el-avatar :size="40" class="ai-avatar">
                  <el-icon><Cpu /></el-icon>
                </el-avatar>
                <div class="ai-details">
                  <h3>云顶AI助手</h3>
                  <p>{{ getFeatureDescription(activeFeature) }}</p>
                </div>
              </div>
              <div class="chat-actions">
                <el-button circle @click="toggleVoice">
                  <el-icon><Microphone /></el-icon>
                </el-button>
              </div>
            </div>

            <div class="chat-messages" ref="chatContainer">
              <div v-if="messages.length === 0" class="welcome-message">
                <div class="welcome-content">
                  <el-icon size="60" color="#409eff"><Cpu /></el-icon>
                  <h3>欢迎使用云顶AI助手</h3>
                  <p>我可以帮助您制定学习计划、解答问题、分析学习状态等</p>
                  <div class="quick-start">
                    <el-button
                      v-for="prompt in quickPrompts"
                      :key="prompt"
                      size="small"
                      @click="sendQuickPrompt(prompt)"
                    >
                      {{ prompt }}
                    </el-button>
                  </div>
                </div>
              </div>

              <div
                v-for="message in messages"
                :key="message.id"
                class="message"
                :class="{
                  'user-message': message.type === 'user',
                  'ai-message': message.type === 'ai',
                }"
              >
                <div class="message-avatar">
                  <el-avatar v-if="message.type === 'user'" :size="32">
                    {{ currentUser?.nickname?.charAt(0) }}
                  </el-avatar>
                  <el-icon v-else color="#409eff" size="32"><Cpu /></el-icon>
                </div>
                <div class="message-content">
                  <div class="message-text" v-html="message.content"></div>
                  <div class="message-time">
                    {{ formatTime(message.timestamp) }}
                  </div>
                </div>
              </div>

              <div v-if="isTyping" class="typing-indicator">
                <div class="typing-avatar">
                  <el-icon color="#409eff" size="32"><Cpu /></el-icon>
                </div>
                <div class="typing-content">
                  <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>

            <div class="chat-input">
              <div class="input-container">
                <el-input
                  v-model="currentMessage"
                  placeholder="输入您的问题..."
                  type="textarea"
                  :rows="2"
                  @keydown.enter.prevent="handleEnter"
                  @input="handleInput"
                />
                <div class="input-actions">
                  <el-button circle @click="attachFile">
                    <el-icon><Paperclip /></el-icon>
                  </el-button>
                  <el-button
                    type="primary"
                    circle
                    :loading="isTyping"
                    @click="sendMessage"
                  >
                    <el-icon><Promotion /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧信息面板 -->
          <div class="info-panel">
            <div class="panel-section">
              <h4>对话统计</h4>
              <div class="stats">
                <div class="stat-item">
                  <span class="stat-label">今日对话</span>
                  <span class="stat-value">{{ todayChats }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">解决问题</span>
                  <span class="stat-value">{{ solvedProblems }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">学习建议</span>
                  <span class="stat-value">{{ studySuggestions }}</span>
                </div>
              </div>
            </div>

            <div class="panel-section">
              <h4>常用功能</h4>
              <div class="common-features">
                <el-button size="small" @click="createStudyPlan"
                  >制定学习计划</el-button
                >
                <el-button size="small" @click="analyzeProgress"
                  >分析学习进度</el-button
                >
                <el-button size="small" @click="generateQuestions"
                  >生成练习题</el-button
                >
                <el-button size="small" @click="summarizeNotes"
                  >整理笔记</el-button
                >
              </div>
            </div>

            <div class="panel-section">
              <h4>学习建议</h4>
              <div class="suggestions">
                <div
                  v-for="suggestion in suggestions"
                  :key="suggestion.id"
                  class="suggestion-item"
                >
                  <el-icon size="16" color="#67c23a"><Check /></el-icon>
                  <span>{{ suggestion.text }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- <AppFooter /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";
import {
  Cpu,
  ChatDotRound,
  Document,
  TrendCharts,
  QuestionFilled,
  EditPen,
  Microphone,
  Paperclip,
  Promotion,
  Check,
} from "@element-plus/icons-vue";

const userStore = useUserStore();

const activeFeature = ref("chat");
const currentMessage = ref("");
const isTyping = ref(false);
const chatContainer = ref<HTMLElement>();

const currentUser = computed(() => userStore.currentUser);

const aiFeatures = ref([
  { id: "chat", name: "智能问答", icon: ChatDotRound },
  { id: "plan", name: "学习计划", icon: Document },
  { id: "analysis", name: "学习分析", icon: TrendCharts },
  { id: "questions", name: "AI出题", icon: QuestionFilled },
  { id: "notes", name: "笔记整理", icon: EditPen },
]);

const messages = ref([]);

const quickPrompts = ref([
  "帮我制定一个学习计划",
  "分析我的学习状态",
  "出几道练习题",
  "整理今天的笔记",
]);

const todayChats = ref(15);
const solvedProblems = ref(8);
const studySuggestions = ref(3);

const suggestions = ref([
  { id: 1, text: "建议增加数学练习时间" },
  { id: 2, text: "可以尝试番茄工作法提高专注度" },
  { id: 3, text: "定期复习已学知识点" },
]);

const selectFeature = (featureId: string) => {
  activeFeature.value = featureId;
  // 根据不同功能显示不同的初始化消息
  initFeature(featureId);
};

const getFeatureDescription = (featureId: string) => {
  const descriptions = {
    chat: "我可以回答您的各种学习问题",
    plan: "让我帮您制定个性化的学习计划",
    analysis: "分析您的学习数据，提供改进建议",
    questions: "根据您的学习内容生成练习题",
    notes: "帮您整理和总结学习笔记",
  };
  return descriptions[featureId] || "智能学习助手";
};

const initFeature = (featureId: string) => {
  // 根据功能类型初始化不同的对话内容
  const initMessages = {
    plan: "我来帮您制定学习计划。请告诉我您的学习目标和可用时间。",
    analysis: "我将分析您的学习数据。您想了解哪方面的学习情况？",
    questions: "我可以为您生成练习题。请告诉我您想练习的科目或知识点。",
    notes: "我可以帮您整理笔记。请上传您的笔记内容或描述需要整理的内容。",
  };

  if (initMessages[featureId]) {
    addMessage("ai", initMessages[featureId]);
  }
};

const addMessage = (type: "user" | "ai", content: string) => {
  const message = {
    id: Date.now().toString(),
    type,
    content,
    timestamp: new Date().toISOString(),
  };
  messages.value.push(message);
  nextTick(() => {
    scrollToBottom();
  });
};

const sendMessage = async () => {
  if (!currentMessage.value.trim()) return;

  const userMessage = currentMessage.value;
  addMessage("user", userMessage);
  currentMessage.value = "";

  // 显示AI正在思考
  isTyping.value = true;

  // 模拟AI回复
  setTimeout(() => {
    const aiResponse = generateAIResponse(userMessage);
    addMessage("ai", aiResponse);
    isTyping.value = false;
  }, 1500);
};

const generateAIResponse = (userMessage: string) => {
  // 简单的AI回复逻辑（实际项目中需要调用AI API）
  const responses = {
    default: "感谢您的问题，我正在为您分析...",
    plan: "根据您的需求，我建议制定以下学习计划：<br/>1. 每天2小时专注学习<br/>2. 定期复习和总结<br/>3. 设置阶段性目标",
    analysis:
      "根据您的学习数据分析：<br/>• 本周学习时长：18小时<br/>• 专注度：85%<br/>• 建议：增加休息频率，提高学习效率",
    questions:
      "为您生成以下练习题：<br/>1. 什么是Vue的响应式原理？<br/>2. 如何实现组件间通信？<br/>3. 解释虚拟DOM的作用",
    notes:
      "您的笔记已整理完成：<br/>• 核心概念：3个<br/>• 重点知识：5个<br/>• 需要复习的内容：2个",
  };

  const lowerMessage = userMessage.toLowerCase();

  if (lowerMessage.includes("计划") || lowerMessage.includes("plan")) {
    return responses.plan;
  } else if (lowerMessage.includes("分析") || lowerMessage.includes("数据")) {
    return responses.analysis;
  } else if (lowerMessage.includes("题目") || lowerMessage.includes("练习")) {
    return responses.questions;
  } else if (lowerMessage.includes("笔记") || lowerMessage.includes("整理")) {
    return responses.notes;
  }

  return responses.default;
};

const sendQuickPrompt = (prompt: string) => {
  currentMessage.value = prompt;
  sendMessage();
};

const handleEnter = (event: KeyboardEvent) => {
  if (!event.shiftKey) {
    sendMessage();
  }
};

const handleInput = () => {
  // 可以添加输入提示逻辑
};

const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
  }
};

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp);
  return `${date.getHours().toString().padStart(2, "0")}:${date
    .getMinutes()
    .toString()
    .padStart(2, "0")}`;
};

const clearChat = () => {
  messages.value = [];
  ElMessage.success("对话已清空");
};

const exportChat = () => {
  ElMessage.info("导出功能开发中");
};

const toggleVoice = () => {
  ElMessage.info("语音功能开发中");
};

const attachFile = () => {
  ElMessage.info("文件上传功能开发中");
};

const createStudyPlan = () => {
  selectFeature("plan");
  addMessage(
    "ai",
    "我来帮您制定学习计划。请告诉我您的学习目标、可用时间和偏好的学习方式。"
  );
};

const analyzeProgress = () => {
  selectFeature("analysis");
  addMessage("ai", "正在分析您的学习进度...");
};

const generateQuestions = () => {
  selectFeature("questions");
  addMessage("ai", "我可以为您生成练习题。请告诉我您想练习的科目或知识点。");
};

const summarizeNotes = () => {
  selectFeature("notes");
  addMessage(
    "ai",
    "我可以帮您整理笔记。请描述您需要整理的内容或上传笔记文件。"
  );
};

onMounted(() => {
  // 添加欢迎消息
  setTimeout(() => {
    addMessage(
      "ai",
      "您好！我是云顶AI助手，很高兴为您服务。我可以帮助您制定学习计划、解答问题、分析学习状态等。有什么可以帮助您的吗？"
    );
  }, 500);
});
</script>

<style scoped>
.ai-assistant {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 20px 0;
}

.ai-layout {
  display: flex;
  height: calc(100vh - 100px);
  gap: 20px;
}

.sidebar {
  width: 280px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.ai-features h3 {
  margin-bottom: 20px;
  color: #2c3e50;
}

.feature-list {
  margin-bottom: 30px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 8px;
}

.feature-item:hover {
  background: #f0f9ff;
}

.feature-item.active {
  background: #409eff;
  color: white;
}

.quick-actions h4 {
  margin-bottom: 16px;
  color: #2c3e50;
}

.quick-actions .el-button {
  display: block;
  width: 100%;
  margin-bottom: 8px;
}

.chat-area {
  flex: 1;
  background: white;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chat-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.ai-avatar {
  background: #f0f9ff;
  color: #409eff;
}

.ai-details h3 {
  margin: 0 0 4px 0;
  color: #2c3e50;
}

.ai-details p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

.welcome-message {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.welcome-content {
  text-align: center;
  max-width: 400px;
}

.welcome-content h3 {
  margin: 16px 0 8px 0;
  color: #2c3e50;
}

.welcome-content p {
  color: #7f8c8d;
  margin-bottom: 24px;
}

.quick-start {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

.message {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.user-message {
  flex-direction: row-reverse;
}

.user-message .message-content {
  background: #409eff;
  color: white;
  border-radius: 16px 16px 4px 16px;
}

.ai-message .message-content {
  background: #f8f9fa;
  border-radius: 16px 16px 16px 4px;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
}

.message-text {
  line-height: 1.6;
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
}

.typing-indicator {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.typing-content {
  background: #f8f9fa;
  border-radius: 16px 16px 16px 4px;
  padding: 12px 16px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  background: #409eff;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%,
  60%,
  100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

.chat-input {
  padding: 20px 24px;
  border-top: 1px solid #e4e7ed;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.input-container .el-textarea {
  flex: 1;
}

.input-actions {
  display: flex;
  gap: 8px;
}

.info-panel {
  width: 300px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.panel-section {
  margin-bottom: 30px;
}

.panel-section h4 {
  margin-bottom: 16px;
  color: #2c3e50;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-label {
  color: #7f8c8d;
  font-size: 14px;
}

.stat-value {
  font-weight: bold;
  color: #409eff;
}

.common-features {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.common-features .el-button {
  width: 100%;
}

.suggestions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 6px;
  font-size: 14px;
}

@media (max-width: 1024px) {
  .ai-layout {
    flex-direction: column;
    height: auto;
  }

  .sidebar,
  .info-panel {
    width: 100%;
  }

  .chat-area {
    height: 60vh;
  }
}
</style>
